using Architecture.Api.Application.Command.UserInfoCommand;
using Architecture.Api.Dtos;
using Architecture.Common;
using Architecture.Domain;
using Architecture.Domain.Services;
using Architecture.Repository.Interface;
using MediatR;
using Microsoft.VisualStudio.Web.CodeGenerators.Mvc.Templates.BlazorIdentity.Pages;

namespace Architecture.Api.Application.CommandHandlers.UserInfoHandler;

public class UserInfoCreateCommandHandler : IRequestHandler<UserLoginCommand, ApiResult<LoginDto>>
{
    private readonly IUserInfoService _userInfoService;
    private readonly JwtTools _jwtTools;
    private readonly IConfiguration _configuration;

    public UserInfoCreateCommandHandler(IUserInfoService userInfoService, JwtTools jwtTools,
        IConfiguration configuration)
    {
        _userInfoService = userInfoService;
        _jwtTools = jwtTools;
        _configuration = configuration;
    }

    public async Task<ApiResult<LoginDto>> Handle(UserLoginCommand request, CancellationToken cancellationToken)
    {
        ApiResult<LoginDto> result = new ApiResult<LoginDto>();
        var user = await _userInfoService.GetUserInfo(new UserInfo()
            { UserName = request.UserName, Password = request.UserPassword });

        if (user != null) //登录成功
        {
            //生成Token
           var token= _jwtTools.JwtNewString(_configuration, user.ID.ToString());
            result.ErrorCode = 0;
            result.Message = token;
            result.Data = new LoginDto() { UserName = user.UserName };
        }
        else
        {
            result.Message = "账号或者密码错误";
        }

        return result;
    }
}